package org.seamon.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.seamon.management.mapper.SmsRecordMapper;
import org.seamon.management.pojo.dto.SmsRecordListDto;
import org.seamon.management.pojo.entity.SmsRecord;
import org.seamon.management.pojo.vo.SmsRecordDetailVo;
import org.seamon.management.pojo.vo.SmsRecordListVo;
import org.seamon.management.service.SmsRecordService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Simon
 * @description 针对表【sms_record(短信发送记录表)】的数据库操作Service实现
 * @createDate 2025-07-11 00:32:35
 */
@Service
public class SmsRecordServiceImpl extends ServiceImpl<SmsRecordMapper, SmsRecord>
        implements SmsRecordService {

    @Override
    public Page<SmsRecordListVo> list(SmsRecordListDto dto) {
        Page<SmsRecord> page = new Page<>(dto.getCurrent(), dto.getSize());
        LambdaQueryWrapper<SmsRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getStatus() != null, SmsRecord::getStatus, dto.getStatus());
        Page<SmsRecord> recordPage = this.page(page, queryWrapper);

        Map<String, List<SmsRecord>> groupedMap = recordPage.getRecords().stream()
                .collect(Collectors.groupingBy(
                        r -> r.getContent() + "_" + r.getStatus() + "_" + r.getCreateTime()
                ));

        List<SmsRecordListVo> voList = groupedMap.values().stream()
                .map(group -> {
                    SmsRecord sample = group.get(0);
                    List<SmsRecordDetailVo> details = group.stream()
                            .map(record -> {
                                SmsRecordDetailVo detail = new SmsRecordDetailVo();
                                detail.setId(record.getId());
                                detail.setPhone(record.getPhone());
                                detail.setResponseCode(record.getResponseCode());
                                detail.setResponseMsg(record.getResponseMsg());
                                return detail;
                            })
                            .collect(Collectors.toList());

                    SmsRecordListVo vo = new SmsRecordListVo();
                    vo.setContent(sample.getContent());
                    vo.setStatus(sample.getStatus());
                    vo.setCreateTime(sample.getCreateTime());
                    vo.setDetails(details);
                    return vo;
                })
                .collect(Collectors.toList());

        Page<SmsRecordListVo> res = new Page<>();
        res.setSize(groupedMap.size());
        res.setCurrent(recordPage.getCurrent());
        res.setTotal(recordPage.getTotal());
        res.setRecords(voList);
        return res;
    }
}




